<?php
namespace app\client\controller;
use app\common\lib\Redis;
use think\swoole\facade\Task;

class Login {
    public function login(){
        
        $params = request()->post();
        if(empty($params)) {
            return errorResult();
        }
        $Test = isset($params['test']) ? trim($params['test']) : '';
        $code = isset($params['code']) ? trim($params['code']) : '';
        if($code === ''){
            return errorResult();
        }
        
        $inviter = isset($params['inviter']) ? intval($params['inviter']) : 0;
        if($inviter < 0) {
            return errorResult();
        }
        
        /* Task::async(function() use($params){
            var_dump($params);
        }); */
        
        $wxConfig = config('config.wx');
        
        $ch = curl_init("https://api.weixin.qq.com/sns/jscode2session?appid={$wxConfig['appid']}&secret={$wxConfig['secret']}&js_code={$code}&grant_type=authorization_code");
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        $result = curl_exec($ch);
        curl_close($ch);

        unset($ch);
        unset($wxConfig);

       if(!$result){ //获取微信信息失败
            return errorResult('登录失败1');
        }
        
        $result = json_decode($result, true);
        
        if(!$result || isset($result['errcode'])){
            if($Test) {
                return errorResult(json_encode($result));
            }else{
                return errorResult('登录失败2');
            }
            
        }
        
        $unionid = isset($result['unionid']) ? trim($result['unionid']) : '';
        $openid = $result['openid'];
        $session_key = $result['session_key'];
        
        $userModel = model('User');
        $time = time();
        
        //用户
        
        $user = $userModel->findOne(['openid' => $openid], 'unionid, nickname, user_id, avatar, sex, user_type, merchant_begin, merchant_annual_expire, background, remark, mobile, wechat, label, city');

        if(empty($user)){ //没有的
            
            $userModel->startTrans();
            
            $data = ['register_time' => $time, 'session_key' => $session_key, 'last_login_time' => $time, 'openid' => $openid, 'unionid' => $unionid];
            if(!empty($unionid)) {
                $data['unionid'] = $unionid;
            }
            
            if($inviter > 0) {
                $data['inviter'] = $inviter;
            }
            
            $userId = $userModel->add($data);
            
            if(!$userId){
                $userModel->rollback();
                return errorResult('登录失败3');
            }
            
            $walletId = model('UserWallet')->add(['user_id' => $userId]);
            
            if(!$walletId){
                $userModel->rollback();
                return errorResult('登录失败4');
            }
            
            $userModel->commit();
            
            $user = ['register_time' => $time, 'mobile' => '', 'user_type' => 0, 'user_id' => $userId, 'isAuth' => false];
        }else{ //已经有了
            //$user['mobile'] = empty($user['mobile']) ? 0 : 1;
            $userId = $user['user_id'];
            $data = ['last_login_time' => $time, 'session_key' => $session_key];
            if(empty($user['unionid']) && !empty($unionid)){
                $data['unionid'] = $unionid;
            }
            $userModel->modify(['user_id' => $userId], $data);
            unset($user['unionid']);
            
            $user['isAuth'] = $user['avatar'] === '';
        }
        
        unset($userModel);
        
        $chatModel = model('Chat');
        Task::async(function() use($userId, $user, &$chatModel) {
            $user['chat_number'] = $chatModel->where(['user_id' => $userId])->count();
            $user['goods_number'] = $chatModel->where(['user_id' => $userId, 'chat_type' => 2])->count();
            unset($chatModel);
            $redis = new Redis();
            $redis->set('user_' . $userId, $user);
            $redis->close();
            
            return true;
        });
        
        $signer = new \Lcobucci\JWT\Signer\Hmac\Sha256();
        $builder = new \Lcobucci\JWT\Builder();
        $builder->setIssuer('易伙');
        $builder->setAudience('易伙');
        $builder->setId($userId * 520, true); //自定义标识
        $builder->setIssuedAt($time);
        $builder->set('key',base64_encode($userId * 1030));
        $builder->sign($signer,config("config.jwtKey"));
        $token = $builder->getToken()->__toString();
        
        return successResult(['token' => $token, 'user' => $user]);
    }
}












